package net.zjitc.controller;

import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.map.MapUtil;
import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import net.zjitc.common.ResponseResult;
import net.zjitc.common.lang.Const;
import net.zjitc.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.Principal;
import java.util.Map;

/**
 * @author 毛钰深
 * @create 2022/1/23
 */
@Slf4j
@RestController
public class AuthController {

    //注入自定义的producer
    @Autowired
    private Producer producer;

    //注入redis工具类
    @Autowired
    private RedisUtil redisUtil;

    @GetMapping("/captcha")
    public ResponseResult captcha() throws IOException {
        //使用hutool工具生成一个随机的32位UUID
        String key= UUID.randomUUID().toString();
        //使用producer生成一个验证码
        String code = producer.createText();

        //生成验证码图片
        BufferedImage image = producer.createImage(code);
        //通过ImageIO将图片以jpg格式写入二进制数组输出流
        ByteArrayOutputStream outputStream =new ByteArrayOutputStream();
        ImageIO.write(image,"jpg",outputStream);

        //将该流改为base64的格式,(前端可以直接使用)
        //前缀
        String pre="data:image/jpeg;base64,";
        //拼接图片
        String base64Img= pre+ Base64Encoder.encode(outputStream.toByteArray());

        //将key和验证码code存放到redis中,最后一个参数是有效时间
        redisUtil.hset(Const.CAPTCHA_KEY,key,code,120);

        log.info("验证码 -- {} - {}", key, code);

        //返回封装的数据
        ResponseResult<Map> res=new ResponseResult<>();
        res.setSuccess(MapUtil.builder()
                .put("key",key)
                .put("captchaImg",base64Img)
                .build()
        );
        return res;
    }

    /**
     * 用户头像信息(username和[暂时还没实现]用户的头像信息)
     * @param principal
     * @return
     */
    @GetMapping("/userInfo")
    public ResponseResult userInfo(Principal principal){
        ResponseResult res=new ResponseResult();
        res.setSuccess(MapUtil.builder()
                .put("username",principal.getName())
                .map()
        );
        return res;
    }
}
